package com.workflow.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.workflow.server.dto.json.ChildNode;
import com.workflow.server.entity.ProcessTemplates;
import com.workflow.server.service.IBpmnService;
import com.workflow.server.service.IFlowNodeCreateHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.FlowNode;
import org.camunda.bpm.model.bpmn.instance.Process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class IBpmnServiceImpl implements IBpmnService {
    @Autowired
    RepositoryService repositoryService;

    @Autowired
    IFlowNodeCreateHandlerContext flowNodeCreateHandlerContext;

    @Override
    public String createBpmnModel(ProcessTemplates oaForms) {
        String processJson = oaForms.getProcess();
        String formId = "Process-" + oaForms.getTemplateId();
        String formName = oaForms.getTemplateName();

        ChildNode childNode = JSONObject.parseObject(processJson, new TypeReference<ChildNode>() {
        });


        log.info("流程设计对应的jsonSchema为:[{}]", processJson);

        BpmnModelInstance bpmnModelInstance = Bpmn.createExecutableProcess(formId).name(formName)
                .id(formId)
                .startEvent()
                .id("StartEvent")
                .name("开始节点")
                .camundaInitiator("${initiator}")
                .done();
        Process process = bpmnModelInstance.getModelElementById(formId);
        FlowNode flowNode = flowNodeCreateHandlerContext.createNode("StartEvent", childNode, process, new HashMap<>());
        String id = flowNode.getId();
        String sequenceFlowId = id + "-" + "EndEvent";

        flowNode.builder()
                .sequenceFlowId(sequenceFlowId)
                .endEvent()
                .id("EndEvent")
                .name("结束节点")
                .done();
        Bpmn.writeModelToStream(System.out, bpmnModelInstance);

        Deployment deploy = repositoryService.createDeployment()
                .name(formName)
                .addModelInstance(formName + ".bpmn20.xml", bpmnModelInstance)
                .deploy();

        log.info("流程设计部署成功,部署id为:[{}]", deploy.getId());
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        String processDefinitionId = processDefinition.getId();
        log.info("流程定义ID为:[{}}", processDefinitionId);


        return formId;
    }
}
